<template>
  <div class="app-container">
    <ContentWrap>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form :model="queryParams" ref="queryForm" size="medium" :inline="true" label-width="68px">
            <el-form-item label="设备编号" prop="deviceNum">
              <el-input
                v-model="queryParams.deviceNum"
                placeholder="请输入设备编号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="上报日期" prop="reportDay">
              <el-date-picker clearable 
                        v-model="queryParams.reportDay"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期">
              </el-date-picker>
            </el-form-item>


            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="medium" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
              <div style="width: 100%;" :style="getMapHeight">
                <L7Map @mapLoaded="handleMapLoaded" :zoom="15">
                </L7Map>
                <div
                  style="position: absolute;top: 40px;right: 30px;display: flex;flex-direction: column;justify-content: center;
                  z-index: 1200;background-color: #FFFFFF;padding: 10px 20px;width: 180px;">

                  <el-row>
                    <el-col :span="8"><div class="grid-content bg-purple">
                       <span style="color: #67C23A;text-align: center;"  class="number-box">{{successDataCount}} </span>
                    </div></el-col>
                    <el-col :span="16"><el-button type="success"  style="width: 100%;"
                       @click="handleMarkerVisibleChange(1)">正 常</el-button></el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="8"><div class="grid-content bg-purple">
                         <span style="color: #ff4949;text-align: center;" class="number-box">{{dangerDataCount}} </span>
                    </div></el-col>
                    <el-col :span="16"><el-button type="danger" style="width: 100%;"  
                       @click="handleMarkerVisibleChange(2)">报 警</el-button></el-col>
                  </el-row>
                   <el-row>
                    <el-col :span="8"><div class="grid-content bg-purple">
                         <span style="color: #E6A23C;text-align: center;" class="number-box">{{warningDataCount}} </span>
                    </div></el-col>
                    <el-col :span="16"><el-button   style="width: 100%;" type="warning" 
                       @click="handleMarkerVisibleChange(3)">疑 似</el-button></el-col>
                  </el-row>
                   <el-row>
                    <el-col :span="8"><div class="grid-content bg-purple">
                          <span style="color: #29abe2;text-align: center;" class="number-box">{{primaryDataCount}} </span>
                    </div></el-col>
                    <el-col :span="16"><el-button style="width: 100%;" type="primary" 
                       @click="handleMarkerVisibleChange(4)">无数据</el-button></el-col>
                  </el-row>
                </div>
              </div>

        </el-col>
      </el-row>

      <LeakDetectionDetailDialog ref="refLeakDetectionDetailDialog"/>
    </ContentWrap>
  </div>
</template>

<script>
import {Marker, MarkerLayer, Popup} from '@antv/l7'
import L7Map from '@/components/L7Maps/map.vue'
import LeakDetectionDetailDialog from '../../components/LeakDetectionDetailDialog.vue'
import {
  listRealtimeGatherData,
} from "@/api/leakage/realtimeGatherData";

import {
  listLedger
} from "@/api/leakage/deviceLedger";

import { formatDateTime } from '@/utils/ruoyi'



export default {
  name: "index",
  components: {L7Map, LeakDetectionDetailDialog},
  data() {
    return {
      // defaultDate: formatDateTime(new Date(),"yyyy-MM-dd"),
      // defaultDate: '2022-05-01',
      successDataCount:0,
      dangerDataCount:0,
      warningDataCount:0,
      primaryDataCount:0,

      successData:[],
      dangerData :[],
      warningData:[],
      primaryData:[],

        // 图层正常
      markerLayerZC: undefined,
      // 图层正常是否可见
      markerVisibleZC: true,


      markerLayerBJ: undefined,
      // 图层报警是否可见
      markerVisibleBJ: true,

      markerLayerYS: undefined,
      // 图层疑似是否可见
      markerVisibleYS: true,


      markerLayerWSJ: undefined,
      // 图层无数据是否可见
      markerVisibleWSJ: true,


      screenHeight: null,
      mapScene: undefined,
      // 定位表数据
      noDataTerminalDataList: [],
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
    
      pressureTerminalDataList: [],
      // 实时数据采集（大）表格数据
      realtimeGatherDataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        deviceNum: null,
        reportDay: null,
      },

      markerList1:[],
      isShow1:true,
      clearable1:false,

      markerList2:[],
      isShow2:true,
      clearable2:false,

      markerList3:[],
      isShow3:true,
      clearable3:false,

      markerList4:[],
      isShow4:true,
      clearable4:false,
    }
  },
  methods: {
    initParams() { 
      this.queryParams.reportDay = formatDateTime(new Date(), 'yyyy-MM-dd')
    },
    handleMapLoaded(scene) {
      this.mapScene = scene
      this.markerLayerZC = new MarkerLayer();
      this.markerLayerBJ = new MarkerLayer();
      this.markerLayerYS = new MarkerLayer();
      this.markerLayerWSJ = new MarkerLayer();
      this.getList()
    },
    
    /** 查询实时数据采集（大）列表 */
    getList() {
      this.loading = true;
      if(!this.queryParams.reportDay){
        this.$message.error('上报日期为必选查询条件，不能为空！')
        return;
      }
      this.$nextTick(() => {
          this.mapScene.removeAllLayer();
          this.markerLayerZC.clear();
          this.markerLayerBJ.clear();
          this.markerLayerYS.clear();
          this.markerLayerWSJ.clear();
      })
      
      // listLedger(Object.assign(this.queryParams,{"reportDay":formatDateTime(new Date(),"yyyy-MM-dd")})).then(res => {
      listLedger(this.queryParams).then(res => {
        this.markerList = res.rows;
        
        this.successData = this.markerList.filter(item => item.monitorStatus == '正常')
        this.dangerData  = this.markerList.filter(item => item.monitorStatus == '预警')
        this.warningData = this.markerList.filter(item => item.monitorStatus == '疑似')
        this.primaryData = this.markerList.filter(item => !item.monitorStatus)

        this.successDataCount = this.successData.length
        this.dangerDataCount  = this.dangerData.length
        this.warningDataCount = this.warningData.length
        this.primaryDataCount = this.primaryData.length
        
        if(this.successData.length > 0 ){
          this.addTerminalMarkerToMap(1)
        }
        if(this.dangerData.length > 0 ){
          this.addTerminalMarkerToMap(2)
        }
        if(this.warningData.length > 0 ){
          this.addTerminalMarkerToMap(3)
        }
        if(this.primaryData.length > 0 ){
          this.addTerminalMarkerToMap(4)
        }
        
         

        this.total = res.total;
        this.loading = false;
      });
    },
    handleClick(tab, event) {
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.markerList1 = [];
      this.markerList2 = [];
      this.markerList3 = [];
      this.markerList4 = [];
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },


     handleMarkerVisibleChange(type) {
      let _isShow = this.isShow1; //是否展示图层
      let _count = this.successDataCount;
      let _markerLayer = this.markerLayerZC;
      if(type === 1){
        this.isShow1 = !_isShow;
        this.successDataCount = _isShow?0:this.successData.length
      }else if(type === 2){
         _count = this.dangerDataCount;  
         _markerLayer = this.markerLayerBJ;
         _isShow = this.isShow2;
         this.isShow2 = !_isShow;
         this.dangerDataCount = _isShow?0:this.dangerData.length

      }else if(type ===3){
        _count = this.warningDataCount;
         _markerLayer = this.markerLayerYS;
         _isShow = this.isShow3;
          this.isShow3 = !_isShow;
          this.warningDataCount = _isShow?0:this.warningData.length
      }else if(type ===4){
        _count = this.primaryDataCount;
        _markerLayer = this.markerLayerWSJ;
         _isShow = this.isShow4;
          this.isShow4 = !_isShow;
          this.primaryDataCount = _isShow?0:this.primaryData.length
      }
      if(_isShow){//从显示转为不显示
          this.mapScene.removeLayer(_markerLayer);
           _markerLayer.clear();
      }else{ 
         this.addTerminalMarkerToMap(type);
      }

    },

    addTerminalMarkerToMap(terminalType) {
      const that = this
      let tempList = this.successData;
      let tempLayer = this.markerLayerZC;
      let tempVisible = this.markerVisibleZC;
      let markerIcon = `/images/deviceZC.png`;
      if(terminalType === 2){
        tempList = this.dangerData;
        tempLayer = this.markerLayerBJ;
        tempVisible = this.markerVisibleBJ;
        markerIcon = `/images/devideBJ.png`;
      } else if(terminalType === 3){
        tempList = this.warningData;
       tempLayer = this.markerLayerYS;
        tempVisible = this.markerVisibleYS;
        markerIcon = `/images/deviceYS.png`;
      }else if(terminalType === 4){
        tempList = this.primaryData;
       tempLayer = this.markerLayerWSJ;
        tempVisible = this.markerVisibleWSJ;
        markerIcon = `/images/deviceWSJ.png`;
      }

      const terminals = tempList.filter(item => item.longitude  && item.latitude);
      if (tempLayer) {
        tempLayer.clear()
      }else{ 
        return;
      }
      let point
      terminals.forEach(t => {
        point = [parseFloat(t.longitude), parseFloat(t.latitude)]
        const markerContent = `<div><img src="${markerIcon}" style="width: 32px;height: 32px;"></div>`
        let el = document.createElement('div')
        el.innerHTML = markerContent
        const marker = new Marker({element: el, draggable: false, offsets: [0, 0]}).setLnglat({
          lng: parseFloat(t.longitude),
          lat: parseFloat(t.latitude)
        })

        const data = t
        console.log("888888888888888888888")
        console.log(t)
        const popup = new Popup({
          title: t.deviceNum,
          maxWidth:400,
          lngLat: {
            lng: parseFloat(t.longitude),
            lat: parseFloat(t.latitude)
          }, 
          offsets: [0, 40],
          closeButton: false,
          html: `<div>
                  <table style="border-collapse:collapse;width:400px;border:1px solid #000;">
                    <tr>
                    <th style="border:1px solid #000;padding:8px;text-align: left;">设备状态</th>
                    <th style="border:1px solid #000;padding:8px;text-align: left;">设备经度</th>
                    <th style="border:1px solid #000;padding:8px;text-align: left;">设备纬度</th>
                    </tr>
                    <tr>
                    <td style="border:1px solid #000;padding:8px;text-align: left;">${data.status?data.status:""}</td>
                    <td style="border:1px solid #000;padding:8px;text-align: left;">${data.longitude?data.longitude:""}</td>
                    <td style="border:1px solid #000;padding:8px;text-align: left;">${data.latitude?data.latitude:""}</td>
                    </tr>
                    <tr>
                    <th style="border:1px solid #000;padding:8px;text-align: left;">所属区域</th>
                    <th style="border:1px solid #000;padding:8px;text-align: left;">安装位置</th>
                    <th style="border:1px solid #000;padding:8px;text-align: left;">安装时间</th》
                    </tr>
                    <tr>
                    <td style="border:1px solid #000;padding:8px;text-align: left;">${data.region?data.region:""}</td>
                    <td style="border:1px solid #000;padding:8px;text-align: left;">${data.installPosition?data.installPosition:""}</td>
                    <td style="border:1px solid #000;padding:8px;text-align: left;">${data.installTime?data.installTime:""}</td>
                    </tr>
                  </table>
                </div>`,
        });
        marker.setPopup(popup)

        marker.on('click', (e) => {
          that.$refs.refLeakDetectionDetailDialog.openDialog(t)
          // e.preventDefault()
          // e.stopPropagation()
        });

        marker.on('mouseover', (e) => {
          tempLayer.getMarkers().forEach(m => m.closePopup())
          marker.openPopup()
        })

        marker.on('mouseout', (e) => {
          // if(this.mapScene.getZoom() <= 16.5){
            marker.closePopup()
          // }
        });

        tempLayer.addMarker(marker);
  
      })
      this.mapScene.addMarkerLayer(tempLayer);
      // if (!tempVisible) {
      //   tempLayer.hide()
      // }
      if(point && point[0] && point[1] ){
        this.mapScene.panTo(point)
      }
      
      
    },

     resizeAllCharts() {
      this.$nextTick(() => {
          // this.$refs.refWaterSupplyStatistics.resizeCharts(this.screenHeight)   
      })
    },


 
  },
  created() {
    
    this.screenHeight = document.body.clientHeight
    this.queryParams.reportDay = formatDateTime(new Date(), 'yyyy-MM-dd')
  },
  computed: {    
    getMapHeight() {
      const h = this.screenHeight - 192
      return {height: h + 'px'}
    },
    getAvailableHeight() {
      return this.screenHeight - 244
    },
  },
  mounted() {
    window.onresize = () => {
      this.screenHeight = document.body.clientHeight
      this.resizeAllCharts()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .l7-popup .l7-popup-content {
  position: relative;
  padding: 16px;
  font-size: 14px;
  color: #FFFFFF;
  background: #5e72af;
  border-radius: 3px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

::v-deep .l7-popup-anchor-bottom .l7-popup-tip {
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
  border-top-color: #5e72af;
  border-bottom: none;
}
.number-box{
    display: flex;
    align-items: center;
    align-items: cent;
    justify-content: center;
    height: 36px;
}
   
</style>
